package com.cljz.peipei.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;

import com.cljz.peipei.R;
import com.cljz.peipei.base.App;
import com.cljz.peipei.base.BaseActivity;
import com.cljz.peipei.model.net.bean.PeopleNumBean;
import com.cljz.peipei.present.activity.BeginP;
import com.jakewharton.rxbinding.view.RxView;

import java.util.Random;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/17.
 */

public class BeginActivity extends BaseActivity<BeginP> {
    private static final long TIME = 1000;
    @BindView(R.id.btn_begin)
    Button btnBegin;
    @BindView(R.id.tv_friend)
    TextView tvFriend;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    private Handler handler = new Handler();


    @Override
    public void initData(Bundle savedInstanceState) {
        getP().getNumber();
        initPermission();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // handler自带方法实现定时器
            int number = Integer.valueOf(tvNumber.getText().toString().replace(",", ""));
            Random random = new Random();
            int randomInt = random.nextInt(90) + 10;
            int nextNumber = number + randomInt;
            handler.postDelayed(this, TIME);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(nextNumber);
            stringBuilder.insert(3, ",");
            tvNumber.setText(stringBuilder);
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_begin;
    }

    @Override
    public BeginP newP() {
        return new BeginP();
    }


    public void showPeopleNum(PeopleNumBean peopleNumBean) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(peopleNumBean.getData()).insert(3, ",");
        tvNumber.setText(stringBuilder);
        handler.postDelayed(runnable, TIME); //每隔1s执行
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(btnBegin)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                            Router.newIntent((Activity) App.getInstance()).to(LoginActivity.class).launch();
                            Router.pop(BeginActivity.this);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        handler = null;
    }
}
